package myself.doit.schedule.v1;

import java.util.Date;

/**
 * Created by bjliuyong on 2017/1/10.
 */
public class CronTask extends Thread  {

    private  Runnable runnable ;
    private String cron;

    private  CronSequenceGenerator cronSequenceGenerator ;

    public CronTask(Runnable runnable, String cron) {
        this.runnable = runnable;
        this.cron = cron;
        this.cronSequenceGenerator = new CronSequenceGenerator(cron);
    }

    @Override
    public void run(){

        Date nextTime = new Date() ;
        Date actTime  = nextTime  ;

        while (true) {

            nextTime = cronSequenceGenerator.next(actTime) ;
            long delayTime = nextTime.getTime() - actTime.getTime() ;
            try {
                Thread.sleep(delayTime);
            } catch (InterruptedException e) {
                //this we should  exit or other , now we ignore this
            }
            actTime = new Date();
            runnable.run();
        }
    }

}
